<script lang="ts" setup>
import type { Recordable } from '@vben/types';

import type {
  OnActionClickParams,
  VxeTableGridOptions,
  VxeGridListeners,
  VxeGridProps,
} from '#/adapter/vxe-table';

import type { DictTypeApi } from '#/api/system/dict/dicttype';
import type { DictDataApi } from '#/api/system/dict/dictdata';
import { reactive, ref } from 'vue';

import { ColPage, Page, useVbenModal, useVbenDrawer } from '@vben/common-ui';
import { Plus } from '@vben/icons';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { gridDictType, deleteDictType } from '#/api/system/dict/dicttype';
import { dictColumns } from './dictdata';
import {
  gridDictData,
  deleteDictData,
  updateDictData,
} from '#/api/system/dict/dictdata';
import { useColumns } from './data';
import Form from './modules/dicttypeform.vue';
import Dictform from './modules/dictform.vue';
import { $t } from '#/locales';
import { Button, message, Modal, Card } from 'ant-design-vue';
//============================================
const [FormDrawer, formDrawerApi] = useVbenDrawer({
  connectedComponent: Dictform,
  destroyOnClose: true,
});
const queryDictType = ref('');
const filterDictType = ref('');
const dictTitle = ref('请选择分类');

/**
 * 状态开关即将改变
 * @param newStatus 期望改变的状态值
 * @param row 行数据
 * @returns 返回false则中止改变，返回其他值（undefined、true）则允许改变
 */
async function onStatusChange(newStatus: number, row: DictDataApi.DictData) {
  const status: Recordable<string> = {
    0: '禁用',
    1: '启用',
  };
  try {
    await confirm(
      `你要将${row.dictName}的状态切换为 【${status[newStatus.toString()]}】 吗？`,
      `切换状态`,
    );
    await updateDictData({ dictId: row.dictId, status: newStatus });
    return true;
  } catch {
    return false;
  }
}

/**
 * 将Antd的Modal.confirm封装为promise，方便在异步函数中调用。
 * @param content 提示内容
 * @param title 提示标题
 */
function confirm(content: string, title: string) {
  return new Promise((reslove, reject) => {
    Modal.confirm({
      content,
      onCancel() {
        reject(new Error('已取消'));
      },
      onOk() {
        reslove(true);
      },
      title,
    });
  });
}
// const gridOptions: VxeGridProps<DictDataApi.DictData> = {
//   checkboxConfig: {
//     highlight: true,
//   },
//   columns: [
//     { title: '序号', type: 'seq', width: 50 },
//     { align: 'center', type: 'checkbox', width: 50 },
//     {
//       align: 'left',
//       title: '字典值',
//       sortable: true,
//       field: 'dictCode',
//       width: 100,
//     },
//     {
//       align: 'left',
//       title: '字典显示信息',
//       field: 'dictName',
//       width: 120,
//     },
//     {
//       field: 'dictTypeName',
//       align: 'left',
//       title: '分类名称',
//       width: 150,
//     },
//     {
//       field: 'status',
//       title: '状态',
//       cellRender: {
//         attrs: { beforeChange: onStatusChange },
//         name: onStatusChange ? 'CellSwitch' : 'CellTag',
//       },
//       width: 80,
//     },
//     { field: 'seq', sortable: true, title: '排序', width: 80 },
//     {
//       field: 'createdTime',
//       formatter: 'formatDateTime',
//       title: '创建时间',
//       width: 150,
//     },
//     {
//       field: 'action',
//       fixed: 'right',
//       slots: { default: 'action' },
//       title: '操作',
//       width: 150,
//     },
//   ],
//   exportConfig: {},
//   height: 'auto',
//   keepSource: false,
//   proxyConfig: {
//     ajax: {
//       query: async ({ page, sort }, formValues) => {
//         if (queryDictType.value) {
//           gridApi2.loading = true;
//           const res = await gridDictData({
//             page: page.currentPage,
//             rows: page.pageSize,
//             dictTypeCode: queryDictType.value,
//             orderBy: {
//               [sort.field]: sort.order,
//             },
//           });
//           gridApi2.loading = false;
//           return res;
//         } else {
//           return [];
//         }
//       },
//     },
//     sort: true,
//   },
//   sortConfig: {
//     defaultSort: { field: 'category', order: 'desc' },
//     remote: true,
//   },
//   toolbarConfig: {
//     custom: true,
//     export: true,
//     // import: true,
//     refresh: true,
//     zoom: true,
//   },
// };
function onDictEdit(row: DictDataApi.DictData) {
  formDrawerApi.setData(row).open();
}

// const [Grid, gridApi2] = useVbenVxeGrid({
//   gridOptions,
// });

/**
 * 表格操作按钮的回调函数
 */
function onDictActionClick({
  code,
  row,
}: OnActionClickParams<DictDataApi.DictData>) {
  switch (code) {
    case 'delete': {
      onDeleteDictData(row);
      break;
    }
    case 'edit': {
      onDictEdit(row);
      break;
    }
  }
}
const [Grid, gridApi2] = useVbenVxeGrid({
  gridOptions: {
    checkboxConfig: {
      highlight: true,
    },
    columns: dictColumns(onDictActionClick, onStatusChange),
    exportConfig: {},
    height: 'auto',
    keepSource: false,
    proxyConfig: {
      ajax: {
        query: async ({ page, sort }, formValues) => {
          if (queryDictType.value) {
            gridApi2.loading = true;
            const res = await gridDictData({
              page: page.currentPage,
              rows: page.pageSize,
              dictTypeCode: queryDictType.value,
              orderBy: {
                [sort.field]: sort.order,
              },
            });
            gridApi2.loading = false;
            return res;
          } else {
            return [];
          }
        },
      },
      sort: true,
    },
    pagerConfig: {
      enabled: true,
    },
    sortConfig: {
      defaultSort: { field: 'category', order: 'desc' },
      remote: true,
    },
    toolbarConfig: {
      custom: true,
      export: true,
      // import: true,
      refresh: true,
      zoom: true,
    },
  } as VxeTableGridOptions,
});

/**
 * 删除字典分类
 * @param row
 */
function onDeleteDictData(row: DictDataApi.DictData) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.dictName]),
    duration: 0,
    key: 'action_process_msg',
  });
  deleteDictData(row.dictId)
    .then(() => {
      message.success({
        content: $t('ui.actionMessage.deleteSuccess', [row.dictName]),
        key: 'action_process_msg',
      });
      refreshDictDataGrid();
    })
    .catch(() => {
      hideLoading();
    });
}

/**
 * 刷新表格
 */
function refreshDictDataGrid() {
  gridApi2.query();
}
function onCreateDict() {
  formDrawerApi.setData({}).open();
}
//============================================

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

/**
 * 编辑字典分类
 * @param row
 */
function onEdit(row: DictTypeApi.DictType) {
  console.log('编辑', row);
  formModalApi.setData(row).open();
}
/**
 * 添加下级字典分类
 * @param row
 */
function onAppend(row: DictTypeApi.DictType) {
  formModalApi.setData({ pDictTypeCode: row.dictTypeCode }).open();
}
/**
 * 创建新字典分类
 */
function onCreate() {
  formModalApi.setData(null);
  formModalApi.open();
}

/**
 * 表格操作按钮的回调函数
 */
function onActionClick({
  code,
  row,
}: OnActionClickParams<DictTypeApi.DictType>) {
  switch (code) {
    case 'append': {
      onAppend(row);
      break;
    }
    case 'delete': {
      onDelete(row);
      break;
    }
    case 'edit': {
      onEdit(row);
      break;
    }
    case 'addChild': {
      onAddData(row);
      break;
    }
  }
}
function onAddData(row: DictTypeApi.DictType) {
  formModalApi.setData({ pDictTypeCode: row.dictTypeCode }).open();
}
/**
 * 删除字典分类
 * @param row
 */
function onDelete(row: DictTypeApi.DictType) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.dictTypeName]),
    duration: 0,
    key: 'action_process_msg',
  });
  deleteDictType(row.dictTypeId)
    .then(() => {
      message.success({
        content: $t('ui.actionMessage.deleteSuccess', [row.dictTypeName]),
        key: 'action_process_msg',
      });
      refreshGrid();
    })
    .catch(() => {
      hideLoading();
    });
}
const gridEvents: VxeGridListeners<DictTypeApi.DictType> = {
  cellClick: ({ row }) => {
    queryDictType.value = row.dictTypeCode;
    dictTitle.value = row.dictTypeName;
    gridApi2.query();
    // message.info(`cell-click: ${row.dictTypeCode}`);
  },
};
const [Grids, gridApi] = useVbenVxeGrid({
  gridEvents,
  // id: 'dictTreeGrid',
  // ref: 'dictDataGridRef',
  gridOptions: {
    columns: useColumns(onActionClick),
    height: 'auto',
    radioConfig: {
      labelField: 'dictTypeId',
      highlight: true,
    },
    rowConfig: {
      isHover: true,
    },
    //stripe: true, // 斑马纹
    keepSource: true,
    pagerConfig: {
      enabled: false,
    },
    proxyConfig: {
      ajax: {
        query: async (_params) => {
          gridApi.setLoading(true);
          const res = await gridDictType();
          gridApi.setLoading(false);
          return res;
        },
      },
    },
    toolbarConfig: {
      custom: false,
      export: false,
      refresh: true,
      zoom: false,
    },
    treeConfig: {
      parentField: 'pDictTypeCode',
      rowField: 'dictTypeId',
      transform: false,
    },
  } as VxeTableGridOptions,
});

/**
 * 刷新表格
 */
function refreshGrid() {
  gridApi.query();
}
const props = reactive({
  leftCollapsedWidth: 5,
  leftCollapsible: true,
  leftMaxWidth: 50,
  leftMinWidth: 20,
  leftWidth: 30,
  resizable: true,
  rightWidth: 70,
  splitHandle: true,
  splitLine: true,
});
const leftMinWidth = ref(props.leftMinWidth || 1);
const leftMaxWidth = ref(props.leftMaxWidth || 100);
</script>
<template>
  <ColPage v-bind="props">
    <template #left="{ isCollapsed, expand }">
      <div v-if="isCollapsed" @click="expand"></div>
      <div
        v-else
        :style="{ minWidth: '230px' }"
        class="border-border bg-card mr-2 rounded-[var(--radius)] border p-2"
      >
        <Page auto-content-height>
          <FormModal @success="refreshGrid" />

          <Grids ref="dictTreeGridRef" id="dictTreeGrid">
            <template #toolbar-tools>
              <Button class="mr-2" type="primary" @click="onCreate">
                <Plus class="size-5" />
                {{ $t('ui.actionTitle.create', ['分类']) }}
              </Button>
            </template>
          </Grids>
        </Page>
      </div>
    </template>
    <Card>
      <Page auto-content-height>
        <FormDrawer @success="refreshDictDataGrid" />
        <Grid
          ref="dictDataGrid"
          :table-title="'【' + dictTitle + '】字典数据'"
          :table-title-help="dictTitle"
        >
          <template #toolbar-tools>
            <Button class="mr-2" type="primary" @click="() => onCreateDict()">
              新增
            </Button>
          </template>
          <template #action="{ row }">
            <Button type="link" @click="() => onDictEdit(row)"> 修改 </Button>
            <Button
              type="link"
              class="text-red-500"
              @click="() => onDeleteDictData(row)"
            >
              删除
            </Button>
          </template>
        </Grid>
      </Page>
    </Card>
  </ColPage>
</template>
